import _ from 'lodash';
import { toast } from '../shared/toast';

const isRequired = (required) => (required ? '' : '?');

const genReqInterface = (data = {}) => {
  let res = [`/** ${data.title} 请求参数类型 */`, 'export interface Req {'];

  (data.req_query || []).forEach((item) => {
    res.push(`  /** ${item.desc} */`);
    res.push(`  ${item.name}${isRequired(item.required === '1')}: StringOrNumber;`);
  });

  res.push('}');
  return res.join('\n');
};
const TYPE_MAP = {
  string: 'string',
  integer: 'number',
};

const genResInterface = (data = {}) => {
  const dataSchema = JSON.parse(data.res_body).properties || {};

  let res = [`/** ${data.title} 响应参数类型 */`, 'export interface Res {'];
  const requiredArr = dataSchema.data.required || [];
  Object.keys(dataSchema?.data?.properties ?? {}).forEach((key) => {
    const item = dataSchema.data.properties[key];
    res.push(`  /** ${item.description} */`);
    res.push(`  ${key}${isRequired(requiredArr.includes(key))}: ${TYPE_MAP[item.type]};`);
  });

  res.push('}');
  return res.join('\n');
};

const get = () => {
  const BaseUrl = window.location.hostname;
  const url = `//${BaseUrl}/api/interface/get`;
  const id = window.location.pathname.split('/').pop();

  return fetch(`${url}?id=${id}`).then((res) => res.json());
};

const create = (htmlStr) => {
  var template = document.createElement('template');
  template.innerHTML = htmlStr.trim();
  return template.content.firstChild;
};

const genBtn = async () => {
  const { data } = await get();

  const req = genReqInterface(data);
  const res = genResInterface(data);

  const tpl = `
<div class='tpl-button' style='position: fixed;right: 0;bottom: 0;padding: 30px;'>
    <button>解析</button>
    <button class='type-req' style='margin-left:10px'>复制请求类型定义</button>
    <button class='type-res' style='margin-left:10px'>复制响应类型定义</button>
    <button class='type-all' style='margin-left:10px'>复制所有类型</button>
    <button class='type-query' style='margin-left:10px'>复制query</button>
    <button class='type-mutation' style='margin-left:10px'>复制mutation</button>
</div>

  `;
  /** @type {HTMLDivElement} */
  let tplBtn = document.querySelector('.tpl-button');
  if (tplBtn) {
    tplBtn.onclick = null;
    tplBtn.parentNode.removeChild(tplBtn);
  }
  tplBtn = create(tpl);

  document.body.append(tplBtn);

  tplBtn.onclick = function (e) {
    const btn = e.target;
    if (btn.tagName !== 'BUTTON') return;

    const actionMap = {
      'type-req': () => copy(req),
      'type-res': () => copy(res),
      'type-all': () => copy(res + '\n\n' + req),
      'type-query': () => copy(jsApiCodeGen(data, 'QueryBuilder')),
      'type-mutation': () => copy(jsApiCodeGen(data, 'MutationBuilder')),
      default: () => genBtn(),
    };
    const action = _.find(actionMap, (v, k) => btn.classList.contains(k)) || actionMap.default;
    action();
    toast(`${btn.innerText}成功`);
  };
};

const copy = (str) => {
  navigator.clipboard.writeText(str);
  console.log('复制成功 , str = ', str);
};

function jsApiCodeGen(data, builder) {
  const path = data.path;
  const name = _.camelCase(path);
  const fetchPath = _.startsWith(path, '/') ? path.substring(1) : path;
  return `
/**
 * ${data.title}
 * @see ${location.href}
 **/
export const ${name}Api = new ${builder}("${fetchPath}");`;
}

genBtn();
